```blade
@extends('dashboard.includes.master')
@section('title', 'Update Template')

@section('css')
    <link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <style>
        #preview-container {
            border: 1px solid #ccc;
            padding: 15px;
            min-height: 200px;
            background: #fff;
            display: none;
        }
        #preview-iframe {
            width: 100%;
            min-height: 200px;
            border: none;
        }
    </style>
@endsection

@section('content')
<div class="col-xl-12">
    <div class="row">
        <div class="col-xl-12">
            <div class="card custom-card">
                @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{ session('success') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif
                @if(session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('error') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif

                <div class="card-body">
                    <form action="{{ route('tempelete.update', $tempelete->id) }}" method="POST" enctype="multipart/form-data" id="mainForm">
                        @csrf
                        @method('PUT')
                        <input type="hidden" name="id" value="{{ $tempelete->id }}">
                        <div class="row gy-4">
                            <div class="mb-3 col-4">
                                <label for="subject" class="form-label">Subject</label>
                                <input class="form-control @error('subject') is-invalid @enderror" type="text" name="subject" value="{{ old('subject', $tempelete->subject) }}">
                                @error('subject')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                            <div>
                                <textarea name="body" id="body" style="display: none;">{!! $tempelete->body !!}</textarea>
                                <div id="toolbar-container">
                                    <span class="ql-formats">
                                        <select class="ql-font"></select>
                                        <select class="ql-size"></select>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-bold"></button>
                                        <button class="ql-italic"></button>
                                        <button class="ql-underline"></button>
                                        <button class="ql-strike"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <select class="ql-color"></select>
                                        <select class="ql-background"></select>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-script" value="sub"></button>
                                        <button class="ql-script" value="super"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-header" value="1"></button>
                                        <button class="ql-header" value="2"></button>
                                        <button class="ql-blockquote"></button>
                                        <button class="ql-code-block"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-list" value="ordered"></button>
                                        <button class="ql-list" value="bullet"></button>
                                        <button class="ql-indent" value="-1"></button>
                                        <button class="ql-indent" value="+1"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-direction" value="rtl"></button>
                                        <select class="ql-align"></select>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-link"></button>
                                        <button class="ql-image"></button>
                                        <button class="ql-video"></button>
                                        <button class="ql-formula"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-clean"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button type="button" id="preview-btn" class="btn btn-secondary">Preview HTML</button>
                                    </span>
                                </div>
                                <div id="editor" style="min-height: 200px;"></div>
                                <div id="preview-container"></div>
                                @error('body')
                                    <span class="text-danger d-block mt-2">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="col-12 mt-4">
                            <button type="submit" class="btn btn-primary">Update</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('js')
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/xml.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM fully loaded');

        // Initialize toastr options
        toastr.options = {
            closeButton: true,
            progressBar: true,
            positionClass: 'toast-top-right'
        };

        let quill = null;
        try {
            const editorElement = document.querySelector('#editor');
            if (!editorElement) {
                console.error('Editor element #editor not found');
                return;
            }

            // Register highlight.js with Quill for HTML syntax
            hljs.configure({ languages: ['html', 'xml'] });
            quill = new Quill('#editor', {
                modules: {
                    syntax: {
                        highlight: (text) => hljs.highlight(text, { language: 'html' }).value
                    },
                    toolbar: '#toolbar-container',
                },
                placeholder: 'Enter your HTML or text here...',
                theme: 'snow'
            });
            console.log('Quill initialized successfully');
        } catch (error) {
            console.error('Failed to initialize Quill:', error);
            return;
        }

        const form = document.getElementById('mainForm');
        const bodyTextarea = document.getElementById('body');
        const previewBtn = document.getElementById('preview-btn');
        const previewContainer = document.getElementById('preview-container');
        const editorContainer = document.getElementById('editor');

        if (!form || !bodyTextarea || !previewBtn || !previewContainer || !editorContainer) {
            console.error('Required elements not found:', {
                form: !!form,
                bodyTextarea: !!bodyTextarea,
                previewBtn: !!previewBtn,
                previewContainer: !!previewContainer,
                editorContainer: !!editorContainer
            });
            return;
        }

        // Initialize editor with raw content
        const initialContent = bodyTextarea.value;
        if (initialContent) {
            quill.setText(initialContent + '\n'); // Show raw HTML tags exactly as stored
        } else {
            quill.setContents({ ops: [{ insert: '\n' }] });
        }

        // Function to detect and format URLs and phone numbers
        function applyLinkFormatting(delta) {
            const Delta = window.Quill.import('delta') || function() {
                return { ops: [] };
            };
            const urlRegex = /(https?:\/\/[^\s<]+|www\.[^\s<]+|[^\s<]+\.(com|org|net|au|edu|gov)[^\s+]*)?/gi;
            const phoneRegex = /(\+?\d{1,3}[\s-]?\d{3,4}[\s-]?\d{3,4}[\s-]?\d{3,4})/g;

            const plainText = delta.ops.reduce((text, op) => text + (op.insert || ''), '');
            let newDelta = new Delta();

            const lines = plainText.split('\n').filter(line => line.trim() !== '');
            if (lines.length > 0) {
                newDelta.insert(lines[0], { header: 1 });
                newDelta.insert('\n');
                lines.shift();
            }

            lines.forEach((line, index) => {
                if (!line.trim()) {
                    newDelta.insert('\n');
                    return;
                }

                let lastIndex = 0;
                const matches = [];
                let match;

                while ((match = urlRegex.exec(line)) !== null) {
                    matches.push({ index: match.index, text: match[0], type: 'url' });
                }
                urlRegex.lastIndex = 0;
                while ((match = phoneRegex.exec(line)) !== null) {
                    matches.push({ index: match.index, text: match[0], type: 'phone' });
                }
                phoneRegex.lastIndex = 0;
                matches.sort((a, b) => a.index - b.index);

                matches.forEach(match => {
                    if (lastIndex < match.index) {
                        newDelta.insert(line.slice(lastIndex, match.index));
                    }
                    if (match.type === 'url') {
                        const formattedUrl = match.text.startsWith('http') ? match.text : `https://${match.text}`;
                        newDelta.insert(match.text, { link: formattedUrl });
                    } else if (match.type === 'phone') {
                        const cleanPhone = match.text.replace(/[\s-]/g, '');
                        newDelta.insert(match.text, { link: `tel:${cleanPhone}` });
                    }
                    lastIndex = match.index + match.text.length;
                });

                if (lastIndex < line.length) {
                    newDelta.insert(line.slice(lastIndex));
                }

                if (index < lines.length - 1) {
                    newDelta.insert('\n');
                }
            });

            return newDelta;
        }

        // Function to check if content is HTML
        function isHtmlContent(text) {
            const htmlRegex = /<[a-z][\s\S]*>/i;
            return htmlRegex.test(text.trim());
        }

        // Function to check if content is a full HTML document
        function isFullHtmlDocument(text) {
            const doctypeRegex = /<!DOCTYPE\s+html>/i;
            const htmlTagRegex = /<html[\s\S]*>/i;
            return doctypeRegex.test(text.trim()) || htmlTagRegex.test(text.trim());
        }

        // Function to render HTML in an iframe
        function renderHtmlInIframe(htmlContent, container) {
            try {
                // Create or reuse iframe
                let iframe = container.querySelector('#preview-iframe');
                if (!iframe) {
                    iframe = document.createElement('iframe');
                    iframe.id = 'preview-iframe';
                    container.appendChild(iframe);
                }
                const doc = iframe.contentDocument || iframe.contentWindow.document;
                doc.open();
                doc.write(htmlContent);
                doc.close();
                console.log('Rendered HTML in iframe:', htmlContent);
            } catch (error) {
                console.error('Error rendering HTML in iframe:', error);
                container.innerHTML = '<p style="color: red;">Invalid HTML content</p>';
            }
        }

        // Toggle between editor and preview
        let isPreviewMode = false;
        previewBtn.addEventListener('click', function(event) {
            event.preventDefault();
            if (!quill || !quill.root) {
                console.error('Quill is not initialized or root is undefined');
                return;
            }

            isPreviewMode = !isPreviewMode;
            if (isPreviewMode) {
                previewBtn.textContent = 'Back to Editor';
                editorContainer.style.display = 'none';
                previewContainer.style.display = 'block';
                const rawText = quill.getText().trim();
                if (isHtmlContent(rawText)) {
                    if (isFullHtmlDocument(rawText)) {
                        // Render full HTML document in iframe
                        renderHtmlInIframe(rawText, previewContainer);
                    } else {
                        // Render partial HTML snippet directly
                        try {
                            previewContainer.innerHTML = rawText;
                            console.log('Previewing partial HTML:', rawText);
                        } catch (error) {
                            console.error('Error rendering partial HTML:', error);
                            toastr.error('Invalid HTML content');
                            previewContainer.innerHTML = '<p style="color: red;">Invalid HTML content</p>';
                        }
                    }
                } else {
                    // Render Quill's formatted HTML for plain text
                    const htmlContent = quill.root.innerHTML;
                    previewContainer.innerHTML = htmlContent;
                    console.log('Previewing formatted HTML:', htmlContent);
                }
            } else {
                previewBtn.textContent = 'Preview HTML';
                editorContainer.style.display = 'block';
                previewContainer.style.display = 'none';
                previewContainer.innerHTML = '';
            }
        });

        // Handle text changes and update textarea
        quill.on('text-change', function() {
            try {
                const currentText = quill.getText();
                if (!isHtmlContent(currentText)) {
                    // Apply link formatting only for non-HTML content
                    if (currentText.match(/(https?:\/\/|www\.|\.(com|org|net|au|edu|gov)|\+?\d{1,3}[\s-]?\d{3,4})/)) {
                        const cursorPosition = quill.getSelection()?.index || 0;
                        const delta = quill.getContents();
                        const newDelta = applyLinkFormatting(delta);
                        quill.setContents(newDelta, 'silent');
                        quill.setSelection(cursorPosition, 0, 'silent');
                    }
                    bodyTextarea.value = quill.root?.innerHTML || '';
                } else {
                    // Store raw HTML for HTML content
                    bodyTextarea.value = quill.getText().trim();
                }
                console.log('Text changed - Textarea value:', bodyTextarea.value);
            } catch (error) {
                console.error('Text change error:', error);
            }
        });

        // Handle form submission
        form.addEventListener('submit', function(event) {
            event.preventDefault();
            console.log('Submit button clicked');
            if (!quill || !quill.root) {
                console.error('Quill is not initialized or root is undefined');
                return;
            }

            try {
                const currentText = quill.getText();
                if (!isHtmlContent(currentText)) {
                    const delta = quill.getContents();
                    const formattedContent = applyLinkFormatting(delta);
                    quill.setContents(formattedContent, 'silent');
                    bodyTextarea.value = quill.root.innerHTML || '';
                } else {
                    bodyTextarea.value = quill.getText().trim();
                }
                console.log('Form submit - Textarea value:', bodyTextarea.value);
                const formData = new FormData(form);
                console.log('Form data being sent:', Object.fromEntries(formData));
                form.submit();
            } catch (error) {
                console.error('Form submission error:', error);
            }
        });

        // Set CSRF token for AJAX requests
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    });
</script>
<meta name="csrf-token" content="{{ csrf_token() }}">
@endsection
```